package com.panshi.hujin2.httpcrawler.util.outlook;

import com.panshi.hujin2.httpcrawler.crawler.OutlookCrawler;
import com.panshi.hujin2.httpcrawler.domain.outlook.OutlookInboxDo;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 微软邮箱session解析工具
 * @Author: wangxl
 * @Date: 2018/11/21 9:22
 */
public class OutlookSessionUtil {

    private static Logger logger = LoggerFactory.getLogger(OutlookSessionUtil.class);
    /**
     * 解析session数据，获取收件箱唯一ID
     * @param responseContent
     * @return
     */
    public static OutlookInboxDo getConversationInfo(String responseContent){

        logger.info("解析outlook session content");

        JsonParser jsonParser = new JsonParser();

        JsonElement jsonElement = jsonParser.parse(responseContent);

        JsonObject jsonObject = jsonElement.getAsJsonObject();

        //用户邮箱地址
        String userEmailAddress = jsonObject.getAsJsonObject("owaUserConfig").getAsJsonObject("SessionSettings").get("UserEmailAddress").toString();
        userEmailAddress = userEmailAddress.replaceAll("\"","");

        //下载token
        String downloadToken = jsonObject.getAsJsonObject("owaUserConfig").getAsJsonObject("ApplicationSettings").get("FirstDownloadToken").toString();
        downloadToken = downloadToken.replaceAll("\"","");


        JsonObject responseMessages = jsonObject.getAsJsonObject("findFolders").getAsJsonObject("Body").getAsJsonObject("ResponseMessages");
        //当前session中邮件会话集合
        JsonArray items = responseMessages.getAsJsonArray("Items");
        JsonObject item = items.get(0).getAsJsonObject();
        JsonArray folders = item.getAsJsonObject("RootFolder").getAsJsonArray("Folders");
        JsonObject inbox = folders.get(0).getAsJsonObject();

        JsonObject folderId = inbox.getAsJsonObject("FolderId");
        String totalCount = inbox.get("TotalCount").toString();

        String id = folderId.get("Id").toString();

        return new OutlookInboxDo(userEmailAddress,id,Integer.valueOf(totalCount),downloadToken);
    }

    public static void main(String args[]){
        getConversationInfo("111");
    }
}
